<template>
  <list-card>
    <el-form ref="queryForm" slot="search" inline :model="queryParams" label-suffix="：" size="small">
      <el-form-item label="标签编码" prop="code">
        <el-input v-model="queryParams.code" clearable placeholder="请输入标签编码" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入标签名称" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item class="search-btn">
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" type="info" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div slot="operator">
      <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-sort" size="mini" @click="toggleExpandAll">折叠</el-button>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/> -->
    </div>

    <el-table v-if="refreshTable" slot="list" v-loading="loading" :data="dataList" :lazy="true" :load="treeLoad"
              :tree-props="{children: 'children', hasChildren: 'hasChild'}" class="list-table" row-key="id"
              @selection-change="select">
      <el-table-column v-if="isSelect" align="center" type="selection" width="40"/>
      <el-table-column label="标签名称" min-width="200px" prop="name" show-overflow-tooltip/>
      <el-table-column label="标签编码" min-width="120px" prop="code" show-overflow-tooltip/>
      <el-table-column label="排序" min-width="50px" prop="orderNum"/>
      <el-table-column label="说明" min-width="160px" prop="remark" show-overflow-tooltip/>
      <el-table-column class-name="small-padding fixed-width" fixed="right" label="操作" min-width="160px">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" size="mini" type="text" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.level < 3" icon="el-icon-plus" size="mini"
                     type="text" @click="handleAdd(scope.row)">新增
          </el-button>
          <el-button v-if="scope.row.pid != 0" icon="el-icon-delete" size="mini"
                     type="text" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" :needMax="false" width="800px" @confirm="submitForm"
               @cancel="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-suffix="：" label-width="80px">
        <el-row>
          <!--          <el-col v-if="form.pid !== 0" :span="24">-->
          <!--            <el-form-item label="上级标签" prop="pid">-->
          <!--              <treeselect v-model="form.pid" :options="tagOptions" placeholder="选择上级标签"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="标签名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入标签名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入标签编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签说明" prop="remark">
              <el-input v-model="form.remark" controls-position="right" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button type="info" @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>
  </list-card>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {child, treeselect} from "@/api/tree";
import {checkExist, getInfo, remove, save} from "@/api/base";

export default {
  name: "Tag",
  dicts: [],
  components: {Treeselect},
  props: {
    isSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      baseUrl: '/system/tag/',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      dataList: [],
      // 部门树选项
      tagOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "字典编码不能为空", trigger: "blur"},
          {min: 2, max: 30, message: '长度在2到32个字符', trigger: 'blur'},
          {pattern: /^-?\w+$/, message: '只能包含数字、字母、下划线', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              checkExist('/system/tag/', {'id': this.form.id, 'code': value}).then(res => {
                callback()
              }).catch(err => {
                callback(new Error(err))
              })
            }
          }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      child(this.baseUrl, 0, this.queryParams).then(response => {
        response.data[0].level = 0
        this.dataList = response.data;
        this.loading = false;
      });
    },
    // 树形动态加载表单数据：
    treeLoad(tree, treeNode, resolve) {
      setTimeout(() => {
        child(this.baseUrl, tree.id, this.queryParams).then((res) => {
          console.log(tree, treeNode);
          return resolve(res.data.map(item => ({...item, level: tree.level + 1})));
        });
      }, 222);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        pid: undefined,
        name: undefined,
        code: undefined,
        orderNum: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.pid = row.id;
      }
      this.open = true;
      this.title = "新建标签";
      treeselect(this.baseUrl).then(response => {
        this.tagOptions = response.data.datas;
      });
      // this.getList();
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getInfo(this.baseUrl, row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标签";
      });
      treeselect(this.baseUrl).then(response => {
        this.tagOptions = response.data.datas;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          save(this.baseUrl, this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.getList();
            this.open = false;
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(() => {
        remove(this.baseUrl, row.id).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      });
    },
    select(arr) {
      this.$emit('change', arr)
    }
  }
};
</script>
